package com.gxljc.bear.crawler.cli;

import com.gxljc.commons.quartz.QuartzExecutor;
import com.gxljc.commons.quartz.QuartzJobUtils;
import com.gxljc.commons.util.AdvCli;
import com.gxljc.commons.util.CliRunner;
import com.gxljc.bear.crawler.weixin.MonitorPage;
import org.apache.commons.cli.CommandLine;
import org.apache.commons.cli.Options;
import org.apache.log4j.Logger;


/**
 * 微信爬虫.
 */
public class WeixinMonitorCli implements QuartzExecutor, CliRunner {
    public static final Logger LOG = Logger.getLogger(WeixinMonitorCli.class);

    // 每天23时触发
    private static final String CRON_EXP1 = "0 30 9,23 * * ?";


    @Override
    public Options initOptions() {
        Options options = new Options();
        options.addOption(AdvCli.CLI_PARAM_HELP, false, "WeixinMonitorCli print help message");
        // run periodically
        options.addOption("quartz", false, "run in quartz mode");
        options.addOption("once", false, "run in once mode");
        return options;
    }

    @Override
    public boolean validateOptions(CommandLine cmdLine) {
        return true;
    }

    @Override
    public void start(CommandLine cmdLine) {
        // if there is no type parameter, do not run the program
        if (cmdLine.hasOption("quartz")) {
            try {
                LOG.info("Create Quartz Job of WeixinMonitor.");
                QuartzJobUtils.createQuartzJob(CRON_EXP1, "WeixinMonitorCli", this);
                LOG.info("Finish Create Quartz Job of WeixinMonitor.");
            } catch (Exception e) {
                e.printStackTrace();
            }
        } else if (cmdLine.hasOption("once")) {
            execute();
        }
    }

    @Override
    public void execute() {
        LOG.info("Execute Monitor Rsync.");
        try {
            new MonitorPage().monitor();
        } catch (Exception e) {
            e.printStackTrace();
        }
        LOG.info("Weixin Monitor done.");
    }

    public static void main(String[] args) {
        AdvCli.initRunner(args, "WeixinMonitorCli", new WeixinMonitorCli());
    }
}
